package in.antany.eclipse.timezone.widget;

import java.util.Date;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;

public class ClockWidget extends Canvas {

	final int[] clockArray = { 60, 30, 0, 330, 300, 270, 240, 210, 180, 150,
			120, 90 };
	final int circleRadius = 81;
	final int circleWidth = 5;

	public ClockWidget(Composite parent, int style) {
		super(parent, style);
		addPaintListener(new PaintListener() {

			@Override
			public void paintControl(PaintEvent e) {
				e.gc.setForeground(new Color(e.gc.getDevice(), new RGB(105,
						105, 165)));
				e.gc.setLineWidth(circleWidth);
				e.gc.drawArc(e.x + 10, e.y + 10, circleRadius * 2,
						circleRadius * 2, 0, 360);
				for (int i = 0; i < 12; i++) {
					double xValue = Math.cos((clockArray[i] * Math.PI) / 180)
							* circleRadius;
					int x = (int) (circleRadius + xValue);
					double yValue = Math.sin((clockArray[i] * Math.PI) / 180)
							* circleRadius;
					int y = (int) (circleRadius + (yValue * -1));

					e.gc.drawText(String.valueOf(i + 1), x + (circleWidth), y
							+ (circleWidth));

				}
				int seconds = new Date().getSeconds();
				int minutes = new Date().getMinutes();
				int hours = new Date().getHours();
				int arcSeconds = (15 - seconds) * 6 % 360;
				int arcMinutes = (15 - minutes) * 6 % 360;
				hours = hours > 12 ? hours - 12 : hours;
				Color blue = e.display.getSystemColor(SWT.COLOR_BLUE);
				e.gc.setBackground(blue);

				e.gc.fillArc(e.x + 10, e.y + 10, circleRadius * 2,
						circleRadius * 2, arcSeconds , 2);
				e.gc.fillArc(e.x + 15, e.y + 15, (circleRadius * 2)-10,
						(circleRadius * 2)-10, arcMinutes , 2);
				e.gc.fillArc(e.x + 25, e.y + 25, (circleRadius * 2)-30,
						(circleRadius * 2)-30, clockArray[hours-1] , 2);
				
				
				new Thread("TickTock") {
					public void run() {
						while (!ClockWidget.this.isDisposed()) {
							ClockWidget.this.getDisplay().asyncExec(
									new Runnable() {
										public void run() {
											if (ClockWidget.this != null
													&& !ClockWidget.this
															.isDisposed())
												ClockWidget.this.redraw();
											try{
											Thread.sleep(1000);
											}catch(InterruptedException e){
												return;
											}
										}
									});
							try {
								Thread.sleep(1000);
							} catch (InterruptedException e) {
								return;
							}
						}
					}
				}.start();

			}
		});
	}

}
